<template>
  <div>
    <el-dialog
      width="600px"
      :visible.sync="isShow"
      :show-close="false"
      class="register"
      top
    >
      <div class="title" slot="title">
        用户注册
      </div>
      <el-form
        :model="registerForm"
        ref="registerFormRef"
        :rules="rules"
        label-width="70px"
        label-position="left"
      >
        <el-form-item label="头像" prop="avatar">
          <!--
            action：上传的地址，它上传跟axios没有关系，它是自己封装的，地址要写全
            data：上传时候需要传递的参数，按照接口文档，它的属性名叫 image
            show-file-list：是否展示列表
            before-upload：上传之前，需要做两件事，第一是格式和大小判断，第二把它里面的参数 file 赋值给
                el-upload属性的data中的image
            on-success：上传成功之后，需要做两件事，第一头像上传的框中的图片要变成预览图片(就是给imageUrl)
                      第二件事情是，把上传得到的服务器地址（"file_path":"uploads/20191024/d79f16177aa4d3bf4d2e2398f41c6d68.PNG"）
                      赋值给 registerForm.avatar
           -->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :data="uploadObj"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="registerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" show-password></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="17">
            <el-form-item label="图形码" prop="code">
              <el-input v-model="registerForm.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left:10px">
            <img
              :src="codeUrl"
              style="width:100%;height:40px;"
              @click="changeCodeUrl"
              alt=""
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="17">
            <el-form-item label="验证码" prop="rcode">
              <el-input v-model="registerForm.rcode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left:10px">
            <el-button @click="getRcode">获取用户验证码</el-button>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="register">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Register',
  data () {
    return {
      isShow: false, //决定Dialog显示
      // 提交给后台模型
      codeUrl: process.env.VUE_APP_BASEURL + 'captcha?type=sendsms', // 图形码url地址
      uploadUrl: process.env.VUE_APP_BASEURL + 'uploads', //上传头像的地址
      imageUrl: '', //要预览的头像地址
      uploadObj: {
        image: ''
      }, // 上传时候需要传递的参数
      registerForm: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        code: '', // 图像码 等下提交给后台删除
        rcode: ''
      },
      // 验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        email: {
          required: true, // 加了这个前面就会有红星星
          /**
           * rule：规则
           * value：用户输入的值
           * callback：决定是否校验ok，如果里面没有接 new Error('xxxx')，callback必须调用
           */
          validator: (rule, value, callback) => {
            // return 阻止代码继续往下执行
            if (!value) {
              return callback(new Error('邮箱不能为空'))
            }
            // eslint禁用
            /* eslint-disable */
            const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
            // eslint启用
            /* eslint-enable */
            if (!reg.test(value)) {
              return callback(new Error('邮箱不合法!'))
            }

            // 校验成功
            callback()
          },
          trigger: 'blur'
        },
        phone: {
          required: true, // 加了这个前面就会有红星星
          validator: (rule, value, callback) => {
            /**
             * rule：规则
             * value：用户输入的值
             * callback：决定是否校验ok，如果里面没有接 new Error('xxxx')，callback必须调用
             */
            if (!value) {
              // return 阻止代码继续往下执行
              return callback(new Error('手机号不能为空!'))
            }

            const reg = /^1[3456789][0-9]{9}$/
            if (!reg.test(value)) {
              // return 阻止代码继续往下执行
              return callback(new Error('手机号不合法!'))
            }

            // 校验ok
            callback()
          },
          trigger: 'blur'
        },
        avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        code: [{ required: true, message: '图形码不能为空', trigger: 'blur' }],
        rcode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
      }
    }
  },
  // 侦听器   某个值的change事件
  watch: {
    isShow (newVal) {
      if (newVal == false) {
        // 关闭窗口的时候
        // 清空表单
        // 重置表单的数据  重置了el-form的model绑定的数据
        this.$refs.registerFormRef.resetFields()
        // this.imageUrl = ''
      }
    }
  },
  methods: {
    register () {
      // 全局校验
      this.$refs.registerFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('验证失败')
        }
        // 发请求
        // 删除不要的属性
        delete this.registerForm.code
        const res = await this.$http.post('/register', this.registerForm)
        console.log(res.code)

        if (res.code === 200) {
          /*  this.$message({
            message: '注册成功',
            type: 'success'
          }) */
          this.$message.success('注册成功')
          // 关掉当前窗口
          this.isShow = false
          // 清空掉内容
          this.$refs.registerFormRef.resetFields()
          this.imageUrl = ''
        } else {
          this.$message.error('注册失败')
        }
      })
    },
    changeCodeUrl () {
      this.codeUrl = `${
        process.env.VUE_APP_BASEURL
      }captcha?type=sendsms&t=${new Date() - 0}`
    },
    async getRcode () {
      if (
        this.registerForm.phone.trim().length == 0 ||
        this.registerForm.code.trim().length === 0
      ) {
        this.$message({
          message: '手机号或图形码不能为空',
          type: 'warning'
        })
        return
      }
      // 发请求
      const res = await this.$http.post('sendsms', {
        code: this.registerForm.code,
        phone: this.registerForm.phone
      })

      if (res.code === 200) {
        this.registerForm.rcode = res.data.captcha
      } else {
        this.$message.error(res.message)
        this.changeCodeUrl()
      }
    },

    /**
     * 头像上传之前的回调
     * file：选取的文件本身
     */
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 给上传的参数中的image赋值
      this.uploadObj.image = file
      return isJPG && isLt2M
    },
    /**
     * 上传成功之后的回调
     * res：上传成功之后，服务器给的响应
     *  {
        "message":"ok",
        "code":200,
        "data":{
        "file_path":"uploads/20191024/d79f16177aa4d3bf4d2e2398f41c6d68.PNG"
        }
      }
      file：选取的文件本身，跟beforeAvatarUpload中的file是一样的
     */
    handleAvatarSuccess (res, file) {
      if (res.code === 200) {
        // 给要提交的模型赋值
        this.registerForm.avatar = res.data.file_path
        // 看预览效果，这个应该是base64的图片格式
        this.imageUrl = URL.createObjectURL(file.raw)

        // 这个是传统的给它赋值一个http的地址
        // this.imageUrl = process.env.VUE_APP_BASEURL + res.data.file_path
      }
    }
  }
}
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    background: linear-gradient(to right, #01c4fa, #1395fa);
    font-size: 14px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    color: #fefefe;
    letter-spacing: 0px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-img {
    text-align: center;
  }
  .code-img {
    width: 100%;
    height: 40px;
  }
  .footer {
    display: block;
    margin-top: 0px auto;
    text-align: center;
  }
  .btn-code {
    width: 100%;
  }
}

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.register-dialog {
  margin-top: 0px !important;
}
</style>
